package com.hzc.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hzc.common.utils.PageUtils;
import com.hzc.gulimall.product.service.CategoryBrandRelationService;
import com.hzc.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzc.common.utils.Query;

import com.hzc.gulimall.product.dao.CategoryDao;
import com.hzc.gulimall.product.entity.CategoryEntity;
import com.hzc.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> menus = entities.stream().filter(menu -> menu.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren(getChilds(menu, entities));
            return menu;
        }).sorted((o1, o2) -> {
            return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort());
        }).collect(Collectors.toList());
        return menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //todo 检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogid) {
        List<Long> path = new ArrayList<>();
        CategoryEntity entity = this.getById(catelogid);
        while (entity.getParentCid() != 0) {
            path.add(entity.getCatId());
            entity = this.getById(entity.getParentCid());
        }
        path.add(entity.getCatId());
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */
    //  @CacheEvict(value = "category", key = "'getLevelOneCategories'")//注意普通字符串一定要加单引号
    @CacheEvict(value = "category", allEntries = true)//将category分区的全部删除
    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    //指定放到哪个分区【按照业务类型划分】
    @Cacheable(value = "category", key = "#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevelOneCategories() {
        List<CategoryEntity> entities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }

    @Cacheable(value = "category", key = "#root.method.name", sync = true)
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        /**
         * 1.空结果缓存，解决缓存穿透
         * 2.设置过期时间（加随机值），解决缓存雪崩
         * 3.加锁，解决缓存击穿
         * */
        //加入缓存,缓存中的数据是json字符串
        return getCatelogListFromDb();
        //  return getCatalogJsonFromDbWithRedissonLock(); 用spring-cache即可，没必要用分布式锁
    }

    public Map<String, List<Catelog2Vo>> getData() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //缓存中没有，查数据库
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatelogListFromDb();
            //查到的数据转为json放在缓存中
            String s = JSON.toJSONString(catalogJsonFromDb);
            redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
            return catalogJsonFromDb;
        } else {
            Map<String, List<Catelog2Vo>> res = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return res;
        }
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        //锁的粒度越细越好
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> res;
        try {
            res = getData();
        } finally {
            lock.unlock();
        }
        return res;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功
            Map<String, List<Catelog2Vo>> res;
            try {
                res = getData();
            } finally {
                String lockVal = redisTemplate.opsForValue().get("lock");
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                //删除锁
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return res;
        } else {
            //加锁失败...重试
            //休眠100ms重试
            try {
                Thread.sleep(100);
            } catch (Exception e) {

            }
            return getCatalogJsonFromDbWithRedisLock();//自旋
        }
    }

    //从数据库查询并封装分类数据
    public Map<String, List<Catelog2Vo>> getCatelogListFromDb() {
        List<CategoryEntity> all = this.baseMapper.selectList(null);
        List<CategoryEntity> levelOne = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0L));
        Map<String, List<Catelog2Vo>> res = levelOne.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), oneEntity -> {
            List<CategoryEntity> levelTwoList = getCategoryByParentCid(all, oneEntity.getCatId());
            List<Catelog2Vo> catelog2Vos = levelTwoList.stream().map(twoEntity -> {
                Catelog2Vo catelog2Vo = new Catelog2Vo(oneEntity.getCatId().toString(), null, twoEntity.getCatId().toString(), twoEntity.getName());
                List<CategoryEntity> levelThreeList = getCategoryByParentCid(all, twoEntity.getCatId());
                List<Catelog2Vo.Catelog3Vo> catelog3Vos = levelThreeList.stream().map(threeEntity -> {
                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(twoEntity.getCatId().toString(), threeEntity.getCatId().toString(), threeEntity.getName());
                    return catelog3Vo;
                }).collect(Collectors.toList());
                catelog2Vo.setCatalog3List(catelog3Vos);
                return catelog2Vo;
            }).collect(Collectors.toList());
            return catelog2Vos;
        }));
        return res;
    }

    //在所有分类中找到父id为parentCid的分类
    public List<CategoryEntity> getCategoryByParentCid(List<CategoryEntity> list, Long parentCid) {
        return list.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }

    //找到root菜单的所有子菜单
    private List<CategoryEntity> getChilds(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childs = all.stream().filter(menu -> menu.getParentCid() == root.getCatId()
        ).map(menu -> {
            menu.setChildren(getChilds(menu, all));
            return menu;
        }).sorted((o1, o2) -> {
            return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort());
        }).collect(Collectors.toList());
        return childs;
    }
}